<template>
  <div class="goods-class">
    <!-- 顶部操作栏 -->
    <!-- 搜索栏 -->
    <el-card class="mb-4">
      <div class="flex justify-between items-center">
        <div class="flex-1 mr-4  flex justify-between items-center" >
          <el-input
          style="max-width: 300px;"
            v-model="searchForm.name"
            placeholder="请输入分类名称"
            clearable
            @clear="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch">查询</el-button>
          </el-input>
        <el-button type="primary" @click="handleAdd" style="margin-left: 60px" v-has="'merchant:productCategory:save'">新增分类</el-button>
        </div>
      </div>
    </el-card>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%;margin-top:15px"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="分类名称" />
      <!-- <el-table-column prop="sort" label="排序" width="100" /> -->
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button
            style="color: #409eff"
            type="text"
            @click="handleEdit(row)"
            v-has="'merchant:productCategory:update'"
          >编辑</el-button>
          <el-button
            type="text"
            style="color: #f56c6c"
            @click="handleDelete(row)"
            v-has="'merchant:productCategory:delete'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="text-align: right; margin-top: 16px;">
      <el-pagination
        :current-page="searchForm.page"
        :page-size="searchForm.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :close-on-click-modal="false" 
      :title="dialogType === 'add' ? '新增分类' : '编辑分类'"
      :visible.sync="dialogVisible"
      width="80%"
      @close="resetForm"
    >
      <el-form
      class="dialog_height"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <!-- <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GoodsClass',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        page: 1,
        pageSize: 10
      },
      // 表格数据
      tableData: [],
      total: 10,
      loading: false,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      form: {
        name: '',
        // sort: 0
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序值', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const params = {
          page: this.searchForm.page,
          size: this.searchForm.pageSize,
          condition: {
            name: this.searchForm.name
          }
        }
        const {data}  = await this.$api.productCategoryList(params)
        this.tableData = data.result
        this.total = data.result.length
      } catch (error) {
        console.error('获取商品分类列表失败：', error)
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleSearch() {
      this.searchForm.page = 1
      this.getList()
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.getList()
    },
    // 新增
    handleAdd() {
        console.log('新增');
      this.dialogType = 'add'
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该分类吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.deleteProductCategory(row.id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除失败：', error)
        }
      }).catch(() => {})
    },
    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.dialogType === 'add') {
              await this.$api.addProductCategory({
                name: this.form.name,
              })
              this.$message.success('新增成功')
            } else {
              await this.$api.editProductCategory({
                name: this.form.name,
                id: this.form.id
              })
              this.$message.success('编辑成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error('保存失败：', error)
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        name: '',
        sort: 0
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog_height{
    height: 50vh;
}
.goods-class {
  padding: 20px;
}
</style>